<template>
    <el-tree :props="props" :load="loadNode" @node-click="onClickNode" @node-contextmenu="showContextMenu" lazy />
    <ul ref="menu" class="dbtree-menu">
        <li @click="exportDBStructure" v-show="menuitems.item1">生成数据库结构SQL</li>
        <li @click="exportTableData" v-show="menuitems.item2">生成表内容SQL</li>
        <li @click="refresh" v-show="menuitems.item8">刷新</li>
        <li @click="showProperty" v-show="menuitems.item9">属性</li>
    </ul>
    <BPMDialog ref="tables_dialog" width="400px" height="600px">
        <TablesVue ref="tables_vue" @close-dialog="closeDialog"></TablesVue>
    </BPMDialog>
</template>

<script lang="ts" setup>
import { ref, reactive } from 'vue';
import type Node from 'element-plus/es/components/tree/src/model/node';
import { invoke } from '@tauri-apps/api/tauri';
import { ElMessage } from 'element-plus';
import BPMDialog from "./BPMDialog.vue";
import bpm from "../common/bpm.js";
import TablesVue from "../views/Tables.vue";

const emits = defineEmits(["onClickNode"]);
const tables_dialog: any = ref(null);
const tables_vue: any = ref(null);

const menuitems = reactive({
    item1: false,
    item2: false,
    item8: true,
    item9: true
});

const props = {
    label: 'name',
    children: 'children',
    isLeaf: 'leaf',
    value: 'id'
}


const loadNode = (node: Node, resolve: (data: any[]) => void) => {
    if (node.level === 0) {
        return invoke("get_simple_connections").then((result: any) => {
            for (let i = 0; i < result.length; i++) {
                result[i].leaf = false;
            }
            resolve(result);
        }).catch(err => {
            console.error(err);
        });
    }
    else if (node.level === 1) {
        return invoke("pgsql_get_databases", { id: node.data.id }).then((result: any) => {
            for (let i = 0; i < result.length; i++) {
                result[i].leaf = false;
                result[i].data_id = node.data.id;
                result[i].c = "database";
                // result[i].children = ;
            }
            resolve(result);
        }).catch(err => {
            console.error(err);
        });
    }
    else if (node.level === 2) {
        return resolve([{ name: "schemas", leaf: false }, { name: "users", leaf: false }]);
    }
    else if (node.level === 3) {
        if (node.data.name == "schemas") {
            return invoke("pgsql_get_schemas", { id: node.parent.data.data_id, database: node.parent.data.name }).then((result: any) => {
                for (let i = 0; i < result.length; i++) {
                    result[i].leaf = false;
                    result[i].c = "schema";
                    // result[i].children = ;
                }
                resolve(result);
            }).catch(err => {
                console.error(err);
            });
        }
    }
    else if (node.level === 4) {
        if (node.data.c == "schema") {
            return resolve([{ name: "tables", leaf: false }, { name: "views", leaf: false }]);
        }
    }
    else if (node.level === 5) {
        if (node.parent.data.c == "schema") {
            if (node.data.name == "tables") {
                return invoke("pgsql_get_tables", { id: node.parent.parent.parent.data.data_id, database: node.parent.parent.parent.data.name, schema: node.parent.data.name }).then((result: any) => {
                    for (let i = 0; i < result.length; i++) {
                        result[i].leaf = false;
                        result[i].c = "table";
                    }
                    resolve(result);
                }).catch(err => {
                    console.error(err);
                });
            }
        }
    }
    else if (node.level === 6) {
        if (node.data.c == "table") {
            return resolve([{ name: "columns", leaf: false }, { name: "constraints", leaf: false }, { name: "indexes", leaf: false }, { name: "RLS Policies", leaf: true }, { name: "rules", leaf: true }, { name: "triggers", leaf: true }]);
        }
    }
    else if (node.level === 7) {
        if (node.parent.data.c == "table") {
            if (node.data.name == "columns") {
                return invoke("pgsql_get_table_columns", { id: node.parent.parent.parent.parent.parent.data.data_id, database: node.parent.parent.parent.parent.parent.data.name, schema: node.parent.parent.parent.data.name, table: node.parent.data.name }).then((result: any) => {
                    for (let i = 0; i < result.length; i++) {
                        result[i].leaf = true;
                        result[i].c = "table_column";
                    }
                    resolve(result);
                }).catch(err => {
                    console.error(err);
                });
            }
        }
    }
    return resolve([]);
}

const showProperty = () => {

}

const menu: any = ref(null);
let currentNode: Node;
const showContextMenu = (event: PointerEvent, data: any, node: Node) => {
    bpm.preventDefault(event);
    if (!("c" in data)) {
        hideConextMenu();
        return;
    }
    currentNode = node;
    if (data.c == "schema") {
        //显示导出数据库
        menuitems.item1 = true;
        menuitems.item2 = true;
    }
    else if (data.c == "table") {
        //显示导出表数据
        menuitems.item1 = false;
        menuitems.item2 = true;
    }
    else {
        menuitems.item1 = false;
        menuitems.item2 = false;
    }
    menu.value.style.display = "block";
    menu.value.style.top = (event.clientY - 40) + "px";
    menu.value.style.left = event.clientX + "px";
    bpm.attachEvent(document.body, "click", hideConextMenu);
}

const hideConextMenu = () => {
    menu.value.style.display = "none";
    bpm.removeEvent(document.body, "click", hideConextMenu);
}

const onClickNode = (nodeData: any) => {
    emits("onClickNode", nodeData);
    // console.log(any)
}

//导出数据库结构
const exportDBStructure = () => {
    if (currentNode.data.c == "schema") {
        invoke("pgsql_export_db_structure", { id: currentNode.parent.parent.data.data_id, database: currentNode.parent.parent.data.name, schema: currentNode.data.name }).then((isOk) => {
            if (isOk) {
                ElMessage({
                    message: "导出成功",
                    type: "success",
                });
            }
        }).catch((err) => {
            console.error(err);
            ElMessage.error(err.message);
        });
    }

}

//导出表数据
const exportTableData = () => {
    let database: any;
    let schema: any;
    let dataId: any;
    if (currentNode.data.c == "schema") {
        database = currentNode.parent.parent.data.name;
        dataId = currentNode.parent.parent.data.data_id;
        schema = currentNode.data.name;
    }
    else if (currentNode.data.c == "table") {
        database = currentNode.parent.parent.parent.parent.data.name;
        dataId = currentNode.parent.parent.parent.parent.data.data_id;
        schema = currentNode.parent.parent.data.name;
    }
    tables_dialog.value.show(`${database}.${schema} 生成表内容`, () => {
        tables_vue.value.loadTables(dataId, database, schema);
    });
}

const closeDialog = () => {
    if (tables_dialog.value.isVisible()) {
        tables_dialog.value.closeDialog();
    }
}

//刷新数据
const refresh = () => {

}
</script>